-module(cus_config).

-include("cus.hrl").
-include("logger.hrl").
-include("ejabberd.hrl").

-export([
    start/0,
    reload/0,
    business_nodes/0,
    access_nodes/0,
    is_business_node/0,
    mysql/0,
    token_redis/0,
    token_redis_size/0,
    redis/0,
    redis_size/0,
    ios/0,
    ios_size/0,
    connect_encrypt/0,
    k3/0,
    app_api/0,
    migrate/0
        ]).


start() ->
    List = ejabberd_config:get_option(cus, fun(X) -> hd(X) end),
    lists:foreach(fun(Item) -> ets:insert(cus_config_tab, parse(Item)) end, List).


parse({connect_encrypt, Value}) ->
    case Value of
        [true, File] ->
            {connect_encrypt, [true, cus_util:decode_private_key(?b2l(File))]};
        _ ->
            {connect_encrypt, [false, undefined]}
    end;
parse(V) ->
    V.


reload() ->
    ejabberd_config:reload_file(),
    List = ejabberd_config:get_option(cus, fun(X) -> hd(X) end),
    ets:delete_all_objects(cus_config_tab),
    lists:foreach(fun(Item) -> ets:insert(cus_config_tab, parse(Item)) end, List).


business_nodes() ->
    look_up(business_nodes).


access_nodes() ->
    look_up(access_nodes).


is_business_node() ->
    ?member(node(), business_nodes()).
    

mysql() ->
    look_up(mysql).


token_redis() ->
    look_up(token_redis).


token_redis_size() ->
    case look_up(token_redis) of
        [] ->
            0;
        V ->
            lists:last(V)
    end.
 

redis() ->
    look_up(redis).
    

redis_size() ->
    case look_up(redis) of
        [] ->
            0;
        V ->
            lists:last(V)
    end.


ios() ->
    look_up(ios).


ios_size() ->
    case look_up(ios) of
        [] ->
            0;
        V ->
            lists:last(V)
    end.
    

connect_encrypt() ->
    look_up(connect_encrypt).


k3() ->
    look_up(k3).


app_api() ->
    ?b2l(look_up(app_api)).


migrate() ->
    look_up(migrate).


look_up(K) ->
    case ets:lookup(cus_config_tab, K) of
        [] ->
            [];
        [{K, V}] ->
            V
    end.
